using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace OA.Common
{
    public class Office
    {
        /// <summary>
        /// list 转excel,调用示例 ToExcel("UserName:用户账号,RealName:姓名",list);
        /// </summary>
        /// <param name="strColumns">以逗号,分隔不同栏位，以冒号:分隔栏位与栏位标题，以分号;分隔不同工作溥</param>
        /// <param name="list"></param>
        public static MemoryStream ToExcel(string strColumns, params System.Collections.IEnumerable[] list)
        {
            string[] sheets = strColumns.Split(';');
            if (sheets.Length != list.Length) throw new Exception("传递的工作溥参数与list个数不一致");

            NPOI.SS.UserModel.IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
            for (int i = 0; i < sheets.Length; i++)
            {                
                var sheet = workbook.CreateSheet();
                var columns=sheets[i].Split(',');
                var row = sheet.CreateRow(0);
                for (int j = 0; j < columns.Length; j++)
                {
                    var col=columns[j].Split(':');
                    var cell=row.CreateCell(j);
                    cell.SetCellValue(col[1]);
                }

                var n = 0;
                foreach (object obj in list[i])
                {
                    row = sheet.CreateRow(++n);
                    for (int j = 0; j < columns.Length; j++)
                    {
                        var col = columns[j].Split(':');
                        var value = ObjectUtils.GetPropertyValue(obj, col[0]);
                        var cell = row.CreateCell(j);
                        cell.SetCellValue(value == null ? "" : value.ToString());
                    }
                }
                
            }
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            return ms;
            
        }

        public static void ToExcel(string fileName, string strColumns, params System.Collections.IEnumerable[] list)
        {
            var stream= ToExcel(strColumns, list);
            FileStream fs = System.IO.File.OpenWrite(fileName);
            stream.WriteTo(fs);
            fs.Close();
            fs.Dispose();
            stream.Close();
            stream.Dispose();
        } 
    }
}
